package com.example.swimmingpool.service.wx;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.example.swimmingpool.config.WxConfig;
import com.example.swimmingpool.constants.RedisConstants;
import com.example.swimmingpool.entity.user.User;
import com.example.swimmingpool.entity.user_auth.UserAuth;
import com.example.swimmingpool.mapper.user.UserMapper;
import com.example.swimmingpool.mapper.user_auth.UserAuthMapper;
import com.example.swimmingpool.util.OkHttpUtil;
import com.example.swimmingpool.util.RedisUtil;
import com.example.swimmingpool.util.TokenUtil;
import com.example.swimmingpool.vo.wx.WxCodeVo;
import com.example.swimmingpool.vo.wx.WxResVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class WxService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private UserAuthMapper userAuthMapper;

    @Resource
    private WxConfig wxConfig;

    @Resource
    private RedisUtil redis;

    public WxResVo getWxResVo(WxCodeVo vo) throws IOException {
        String s = OkHttpUtil.get(wxConfig.getUrl(), wxConfig.getAppid(), wxConfig.getSecret(), vo.getCode());
        return JSON.parseObject(s, WxResVo.class);

    }

    public String wxLogin(WxCodeVo vo) throws IOException {
        var res = getWxResVo(vo);
        var count = new LambdaQueryChainWrapper<>(userAuthMapper)
                .like(UserAuth::getOpenid, res.getOpenid())
                .last("limit 1")
                .count();
        String userId;
        if (count == 0) {
            userId = insertWxUser(res);
        } else {
            UserAuth one = new LambdaQueryChainWrapper<>(userAuthMapper)
                    .select(UserAuth::getUserId)
                    .like(UserAuth::getOpenid, res.getOpenid())
                    .last("limit 1").one();
            userId = String.valueOf(one.getUserId());

        }
        var token = TokenUtil.generateToken();
        log.info(token);
        var key = RedisConstants.SWIMMING_USER + token;
        redis.set(key, userId, RedisConstants.SWIMMING_USER_EXPIRE, TimeUnit.DAYS);
        return token;

    }

    public String insertWxUser(WxResVo res) {

        User user = new User();
        userMapper.insert(user);
        var userId = String.valueOf(user.getId());
        user.setCreateBy(userId);
        user.setUpdateBy(userId);
        userMapper.updateById(user);
        UserAuth userAuth = BeanUtil.copyProperties(res, UserAuth.class);
        userAuth.setUserId(Long.valueOf(userId));
        userAuth.setCreateBy(userId);
        userAuth.setUpdateBy(userId);
        userAuthMapper.insert(userAuth);
        return userId;

    }
}
